<template>
  <article class="page">
    <headerbar>支部相册</headerbar>
    <section class="frame-content-sub no-bg">
      <section class="inner-content pdv-9 pdh-4">
        <div class="input-row-wrap">
          <div class="name">相册名称：</div>
          <input v-model="form.title" type="text" placeholder="请填写相册名称">
        </div>
        <div class="input-row-wrap">
          <div class="name">内容描述：</div>
          <textarea v-model="form.spaceExt" placeholder="请简要描述该相册所展示的支部活动内容" name="" id="" cols="30" rows="10"></textarea>
        </div>
        <div class="input-row-wrap">
          <div class="mgt-5 color-tip mgb-1"><i class="required color-red">严禁上传或录入涉密内容</i></div>
          <div class="name">添加图片：</div>
          <section class="upload-wrap">
            <!--        ios的选择图片-->
            <div v-if="tools.isIos()">
            <cube-upload ref="upload"
                         action=""
                         accept="image/*"
                         :simultaneous-uploads="1"
                         @files-added="addedFile"
                         @file-removed="removeFile"
                         :multiple="!0"
            />
            </div>
            <div v-else >
              <cube-upload ref="upload"
                           action=""
                           accept="mutiimage/*"
                           :simultaneous-uploads="1"
                           @files-added="addedFile"
                           @file-removed="removeFile"
                           :multiple="!0"
              />
            </div>
          </section>

        </div>



        <div class="pdv-6"></div>
        <div @click="save($event)" v-preventReClick="1000" class="default-block-btn">提交</div>
        <div class="pdv-5"></div>
      </section>
    </section>
  </article>
</template>

<script>
export default {
  name: 'albumsAdd',
  data () {
    return {
      spaceId: '',
      form: {
        title: '',
        spaceExt: '',
        annexInfo: '',
        spaceType: '3'
      },
      wellDeleteList: [], // 将要真实删除的文件
      forceList: [], // 之前的文件
      attachmentList: []
    }
  },
  mounted () {
    let id = this.$route.query.id
    this.spaceId = id
    if (id) {
      console.log(this.$store.state.branchDetail)
      this.form.title = this.$store.state.branchDetail.title
      this.form.spaceExt = this.$store.state.branchDetail.ext
      this.attachmentList = this.$store.state.branchDetail.annexList
      this.form.spaceId = id
      this.$store.state.branchDetail.annexList.forEach(v => {
        let data = v
        data.url = this.tools.getImgUrl(v.fileId)
        this.forceList.push(v.fileId)
        this.$refs.upload.files.push(data)
      })
    }
  },
  methods: {
    removeFile (file) {
      console.log('removeFile', file)
      console.log('removeFile', this.attachmentList)
      this.attachmentList.splice(this.attachmentList.findIndex(item => {
        this.wellDeleteList.push(file.id)
        return item.fileId === file.fileId
      }), 1)
      console.log('removeFile', this.attachmentList)
    },
    /*真实删除材料，因此只能在保存时候操作*/
    delSpaceInfoAnnex (ID) {
      let params = {
        'loginId': this.tools.getUserInfo().id,
        'spaceId': this.spaceId,
        'annexId': ID,
      }
      this.fetchService.delSpaceInfoAnnex(params)
    },
    /*每次图片添加、更新都是插入动作*/
    uploadFile (file) {
      let me = this
      console.log('uploadfile', file)
      return new Promise((resolve, reject) => {
        if (file.length < 1) {
          return resolve(true)
        }
        Array.prototype.slice.call(file).forEach((v,index) => {
          console.log(index, file.length, me.attachmentList.length)
          if (!v.file) {
            if (me.attachmentList.length === file.length && index === file.length-1) {
              resolve(true)
            }
            return
          }
          (function (v) {
            let formData = new FormData()
            formData.append('file', v)
            me.fetchService.o_upload(formData).then((res) => {
              if (res.code !== 0) {
                return me.tools.tip(res.message)
              }
              let ret = res.data
              let data = {
                fileid: ret.fileId,
                filename: ret.fileName,
                fileUrl: ret.desc
              }
              me.attachmentList.push(data)
              if (me.attachmentList.length === file.length) {
                resolve(true)
              }
            })
          })(v.file)
        })
      })
    },
    addedFile (file) {
      console.log(file, this.$refs.upload)
    },
    getFileJson (list) {
      console.log(this.forceList)
      let ret = []
      list.forEach(v => {
        let item = {
          fileid: v.fileId || v.fileid,
          filename: v.fileName || v.filename,
          fileUrl:v.fileUrl
        }
        ret.push(item)
        console.log(item.fileid)
      })
      /**
       * 目前接口的编辑功能对文件的逻辑是：每次提交的文件都会新增，也就是说之前的文件在这次提交中再次提交的话，那么查询的时候就会出现重复，所以现在在提交前把之前的文件剔除
       */
      let noForceRet = []
      ret.forEach(item => {
        if (!this.forceList.includes(item.fileid)) {
          noForceRet.push(item)
        }
      })
      return noForceRet
    },
    save (e) {
      if (e.target.disabled) {
        return false
      }
      if (this.form.title === '') {
        return this.tools.tip('请填写标题')
      }
      if (this.form.spaceExt === '') {
        return this.tools.tip('请填写内容')
      }
      if (this.attachmentList.length < 1 && this.$refs.upload.files.length < 1) {
        return this.tools.tip('请选择图片')
      }
      this.tools.showLoading('提交中...')
      this.wellDeleteList.forEach(v => {
        this.delSpaceInfoAnnex(v)
      })
      this.uploadFile(this.$refs.upload.files).then(res => {
        let filesJson = this.getFileJson(this.attachmentList)
        this.form.annexInfo = JSON.stringify(filesJson)
        console.log('---------------this.form.annexInfo=', this.form.annexInfo)
        this.fetchService.saveSpaceInfo(this.form).then(res => {
          this.tools.hideLoading()
          if (res.code !== 0) {
            return this.tools.tip(res.message)
          }
          this.tools.tip('提交成功')
          this.tools.back()
        })
      })
    }
  }
}
</script>
<style scoped>
</style>
